﻿using EasyExcel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WssServer.Domain;

namespace WssServer.Excel
{
    /// <summary>
    /// 打印动作
    /// </summary>
    public class PrintAction
    {

        public static void PrintAction1(string data)
        {
            dynamic dy = JsonConvert.DeserializeObject<dynamic>(data);

            Print(dy);
        }

        public static void Print(SalesOrder salesOrder)
        {
            ExcelDoc Excel = new ExcelDoc();



            //string test = dy.abc;
            Excel.SetCell(1, 7, salesOrder.orderDate);
            Excel.SetCell(2, 1, salesOrder.customerName);
            Excel.SetCell(2, 3, salesOrder.contactPhone.ToString());
            Excel.SetCell(2, 6, salesOrder.shippingNumber);

            int idx = 4;
            int total = salesOrder.products.Count;

            //Excel.Npoi.Sheet.ShiftRows(idx + 1, idx + 6, total);

            for (int i = 0; i < total; i++)
            {
                Product product = salesOrder.products[i];
                Excel.SetCell(idx, 0, product.serialNumber);
                Excel.SetCell(idx, 1, product.material);
                Excel.SetCell(idx, 2, product.sourceSpec);
                Excel.SetCell(idx, 3, ConvertDouble(product.weightQuantity));
                Excel.SetCell(idx, 4, ConvertDouble(product.price));
                string processingFees = ConvertDouble(product.processingFees);
                Excel.SetCell(idx, 5, processingFees.ToString());
                Excel.SetCell(idx, 6, ConvertDouble(product.amount));
                //Excel.SetCell(idx, 7, "2");

                if (i < total - 1)
                {
                    Excel.InsertRow(idx);
                }
                idx++;
            }

            Excel.SetCell(idx, 2, salesOrder.upperCaseSum);

            Excel.SetCell(idx, 6, ConvertDouble(salesOrder.totalAmount));

            idx += 5;

            Excel.SetCell(idx, 4, salesOrder.shippingDate);



            Excel.PrintPreView();
        }

        public static string ConvertDouble(double value)
        {
            string str = Convert.ToString(value);
            int index = str.LastIndexOf(".");
            if (index == -1)
            {
                str = $"{str}.00";
            }
            else
            {
                string end = str.Substring(index + 1);
                if (!string.IsNullOrEmpty(end))
                {
                    string _str = str.Substring(0, index + 1);
                    if (end.Equals("0") || end.Equals("000"))
                    {
                        str = $"{_str}00";
                    }
                    else if (end.Length == 1)
                    {
                        str = $"{str}0";
                    }
                }
            }
            return str;
        }



    }
}
